<template>
  <van-nav-bar title="持仓管理" fixed @click-right="router.go(-1)">
    <template #right>
      <van-icon name="cross" size="18" />
    </template>
  </van-nav-bar>
  <div class="search-wrapper">
    <van-search v-model="productParams.keyword" show-action placeholder="产品代码、产品名称" @search="getProductList(1)">
      <template #action>
        <div class="search-btn" @click="getProductList(1)">搜索</div>
      </template>
    </van-search>
    <van-dropdown-menu>
      <van-dropdown-item v-model="productParams.orderField" :options="orderFieldList" @change="getProductList(1)" />
      <van-dropdown-item v-model="productParams.orderType" :options="orderTypeList" @change="getProductList(1)" />
    </van-dropdown-menu>
  </div>
  <div class="product-index">
    <van-empty v-if="productList.length === 0" image="search" description="没有搜索到持仓信息哦~" />
    <template v-else>
      <van-cell-group v-for="item in productList" :key="item.id" @click="openDetail(item)">
        <van-cell>
          <template #title>
            <div class="name">产品名称：{{ item.productNameAlias || item.productName }}</div>
          </template>
          <template #label>
            <div class="product-item">
              <div class="info-wrapper">
                <div class="code">产品代码：{{ item.productCodeAlias || item.productCode }}</div>
                <div class="time">更新日期：{{ item.netDate ? dayjs(item.netDate).format('YYYY-MM-DD') : '' }}</div>
              </div>
              <div class="content-item income-loss">
                <div class="content-item-value">
                  <span>{{ formatAmountBySize(times(item.holdingUnits, item.currentNetValue)) }}</span>
                  <span class="unit">{{ formatAmountTextBySize(times(item.holdingUnits, item.currentNetValue)) }}</span>
                </div>
                <div class="content-item-title">当前资产</div>
              </div>
              <div class="content-item net-value">
                <div class="content-item-value">
                  <span>{{ item.currentNetValue }}</span>
                </div>
                <div class="content-item-title">单位净值</div>
              </div>
            </div>
            <van-divider dashed></van-divider>
            <div class="btn-wrapper">
              <van-space wrap>
                <van-button type="primary" size="small" @click.stop="editProduct(item, 'edit')">编辑</van-button>
                <van-button type="danger" size="small" @click.stop="deleteProduct(item)">删除</van-button>
                <van-button type="primary" size="small" @click.stop="manageProductNetValue(item)">净值</van-button>
                <van-button type="primary" plain size="small" @click.stop="openTradeLog(item)">交易日志</van-button>
              </van-space>
              <van-space wrap style="display: flex; justify-content: end;">
                <van-button type="primary" size="small" @click.stop="startTrade(item, 1)">买入</van-button>
                <van-button type="danger" size="small" @click.stop="startTrade(item, 2)">卖出</van-button>
                <van-button type="primary" size="small" @click.stop="startDividend(item, 1)">分红再投</van-button>
                <van-button type="danger" size="small" @click.stop="startDividend(item, 2)">分红</van-button>
              </van-space>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
      <van-pagination
        v-if="productTotal > productParams.rows"
        v-model="productParams.page"
        :total-items="productTotal"
        :items-per-page="productParams.rows"
        :show-page-size="5"
        force-ellipses
        @change="getProductList"
      />
    </template>
  </div>

  <van-floating-bubble axis="xy" icon="plus" magnetic="x" @click="editProduct()" />

  <EditProduct ref="EditProductRef" @refresh="getProductList" />
  <ProductDetail ref="ProductDetailRef" @refresh="getProductList" />
  <TradeLog ref="TradeLogRef" />
  <Trade ref="TradeRef" userType="admin" @refresh="getProductList" />
  <Dividend ref="DividendRef" userType="admin" @refresh="getProductList" />
  <NetValue ref="NetValueRef" @refresh="getProductList" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { apiGetProductListForAdmin, apiDeleteProduct } from '@/api/product'
import dayjs from 'dayjs'
import EditProduct from './edit.vue'
import ProductDetail from './detail.vue'
import TradeLog from './log.vue'
import Trade from './trade.vue'
import Dividend from './dividend.vue'
import NetValue from './netValue.vue'
import { useRouter } from 'vue-router'
import { times, minus } from '@/utils/calc'
import { formatAmountBySize, formatAmountTextBySize } from '@/utils/common'
import { showConfirmDialog, showToast } from 'vant'

const router = useRouter()
const productParams = ref({
  page: 1,
  rows: 10,
  keyword: '',
  orderField: 'current_net_value',
  orderType: 'desc'
})
const orderFieldList = [
  {
    text: '单位净值',
    value: 'current_net_value'
  },
  {
    text: '资产金额',
    value: 'holding_units'
  }
]
const orderTypeList = [
  {
    text: '降序',
    value: 'desc'
  },
  {
    text: '升序',
    value: 'asc'
  }
]

const productList = ref([])
const productTotal = ref(0)
const EditProductRef = ref()
const ProductDetailRef = ref()
const TradeLogRef = ref()
const TradeRef = ref()
const DividendRef = ref()
const NetValueRef = ref()

const getProductList = async (page = 1) => {
  productParams.value.page = page
  apiGetProductListForAdmin(productParams.value).then((res) => {
    res.list.forEach(item => {
      item.productProfitLoss = minus(times(item.holdingUnits, item.currentNetValue), item.productCost)
    })
    productList.value = res.list
    productTotal.value = res.total
  })
}

const openDetail = (product) => {
  ProductDetailRef.value.open(product, 2)
}

const editProduct = (product = null, type = 'add') => {
  EditProductRef.value.open(
    product || {
      productName: '',
      productCode: '',
      productNameAlias: '',
      productCodeAlias: '',
      currentNetValue: '',
      netDate: ''
    },
    type
  )
}

const deleteProduct = (product) => {
  if (product.holdingUnits || product.productCost) {
    showToast({
      message: '该产品已持仓，不能删除',
      position: 'top'
    })
    return
  }
  showConfirmDialog({
    title: '删除产品',
    message: '确认删除产品吗？'
  })
    .then(() => {
      apiDeleteProduct({ id: product.id }).then((res) => {
        showToast({
          message: '删除成功',
          position: 'top'
        })
        getProductList()
      })
    })
    .catch(() => {})
}

const openTradeLog = (product) => {
  TradeLogRef.value.open(product)
}

const startTrade = (product, type) => {
  TradeRef.value.open(product, type)
}

const startDividend = (product, type) => {
  DividendRef.value.open(product, type)
}

const manageProductNetValue = (product) => {
  NetValueRef.value.open(product)
}

onMounted(() => {
  getProductList()
})
</script>

<style lang="less" scoped>
.search-wrapper {
  position: fixed;
  top: var(--van-nav-bar-height);
  left: 0;
  right: 0;
  z-index: 1;
  --van-dropdown-menu-shadow: 0px 1px 1px rgba(0, 0, 0, 0.1);
  .search-btn {
    padding-right: 4px;
  }
}
.product-index {
  padding-top: 148px;
  --van-divider-margin: 8px;
  .name {
    font-size: 16px;
    font-weight: 500;
  }
  .product-item {
    position: relative;
    display: flex;
    align-items: center;
    .info-wrapper {
      flex: 1;
      margin-right: 10px;
      .code {
        font-size: 16px;
        color: #323232;
      }
      .time {
        font-size: 14px;
        color: #999999;
        margin-top: 10px;
      }
    }
    .content-item {
      text-align: center;
      height: 100%;
      color: #323232;
      &.net-value {
        min-width: 55px;
      }
      &.income-loss {
        min-width: 100px;
      }

      .content-item-title {
        margin-top: 10px;
      }

      .content-item-value {
        display: flex;
        align-items: baseline;
        justify-content: center;
        font-size: 22px;
        height: 22px;
        line-height: 22px;
        font-weight: bold;

        .unit {
          font-size: 12px;
          margin-left: 2px;
        }
      }
    }
  }
  .btn-wrapper {
    display: flex;
    justify-content: space-between;
    .van-space {
      &:nth-child(2) {
        /deep/ .van-space-item {
          &:nth-child(2) {
            margin-right: 0 !important;
          }
        }
      }
      .van-button {
        width: 70px;
      }
    }
  }
}
</style>
